package com.kelp.codetoolkit.parser

import com.intellij.openapi.components.Service
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.yaml.snakeyaml.Yaml
import java.io.StringReader

/**
 * @author: liuyuebai
 * @date: 2025/9/10 08:46
 * @description:
 */
@Service(Service.Level.PROJECT)
class SpringYmlParser {

    companion object{
        fun getInstance(project: Project): SpringYmlParser {
            return project.getService(SpringYmlParser::class.java)
        }
    }

    private val yamlParser = Yaml()

    /**
     * 解析 YAML 文件并转换为 MutableMap 结构
     */
    fun parseYamlToMap(file: VirtualFile): MutableMap<String, Any> {
        return try {
            // 读取文件内容
            val content = String(file.contentsToByteArray())
            // 使用 SnakeYAML 解析 YAML 内容并转换为可变Map
            val map = yamlParser.load<Map<String, Any>>(StringReader(content)) as? Map<String, Any>
            // 将不可变Map转换为可变Map，如果为null则返回空的可变Map
            map?.toMutableMap() ?: mutableMapOf()
        } catch (e: Exception) {
            mutableMapOf()
        }
    }

    fun getYamlParser(): Yaml {
        return yamlParser
    }
}